package com.itheima.jdbcTransfer.service.impl;


import com.itheima.jdbcTransfer.dao.impl.TransferDaoImpl;
import com.itheima.jdbcTransfer.dao.interFace.TransferDao;
import com.itheima.jdbcTransfer.service.interFace.TransferService;
import com.itheima.jdbcdemo.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class TransferServiceImpl implements TransferService {

    //转账的业务
    @Override
    public String transfer(String forName, String toName, Double money) throws Exception  {
        TransferDao tfd = new TransferDaoImpl();
        Connection con = JDBCUtils.getConnection();
        //开启事务
        con.setAutoCommit(false);
        int i = 0;
        int n = 0;
        try {
            //让forName减钱
            i = tfd.transferDel(con, forName, -money);
            //int a = 3/0;
            //让toName加钱
            n = tfd.transferAdd(con, toName, money);
            con.commit();
        } finally {
            con.rollback();
            con.close();
        }
        if (i * n != 0 ){
            return "转账成功!";
        }else {
            return "转账失败!";
        }
    }
}
